package proxy;

import tm.TransactionManager;

import java.lang.reflect.Proxy;

/**
 * 代理对象工厂，实现事务管控
 * @author wsz
 * @date 2021/10/13 11:16
 **/
public class ProxyFactory {

    private TransactionManager transactionManager;

    public void setTransactionManager(TransactionManager transactionManager) {
        this.transactionManager = transactionManager;
    }

    /**
     * 传入实例bean
     * @param object
     * @return
     */
    public Object getProxy(Object object) {
        return Proxy.newProxyInstance(this.getClass().getClassLoader(), object.getClass().getInterfaces(), (proxy, method, args) -> {
            Object result = null;

            try {
                transactionManager.beginTransaction();
                result = method.invoke(object, args);
                transactionManager.commit();
            } catch (Exception ex) {
                ex.printStackTrace();
                transactionManager.rollback();
                // 向上抛出异常
                throw ex.getCause();
            }

            return result;
        });
    }
}
